﻿using Abp.Authorization;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Runtime.Session;
using ALEXFW.Authorization;
using ALEXFW.BasicModel;
using Castle.Core.Logging;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ALEXFW.ChatHub
{
    public class MessageChat : Hub, ITransientDependency
    {
        public IAbpSession Session { get; set; }
        public ILogger Logger { get; set; }
        public string connGroup = "NoGroup";
        public IRepository<Student, Guid> _studentContext;

        public MessageChat(IRepository<Student, Guid> studentContext)
        {
            Session = NullAbpSession.Instance;
            Logger = NullLogger.Instance;
            _studentContext = studentContext;
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendMessage(string message = "无")
        {
            await Clients.All.SendAsync("getMessage", message);
        }

        /// <summary>
        /// 管理员发送消息
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        [AbpAuthorize(PermissionNames.Pages_Admin)]
        public async Task AdminSendMessage(string message)
        {
            await Clients.All.SendAsync("getMessage", message);
        }

        /// <summary>
        /// 发送消息给未加入实习小组的用户
        /// </summary>
        /// <returns></returns>
        public async Task SendToNoJoinGroup()
        {
            await Clients.Group(connGroup).SendAsync("getMessage", "您当前未加入实习小组，请到申请页面申请加入实习小组");
        }

        public override async Task OnConnectedAsync()
        {
            await base.OnConnectedAsync();
            
            //根据当前登录的用户，判断其是否加入了实习小组，如果没有则加入组
            var student = await _studentContext.FirstOrDefaultAsync(x => x.UserID == Session.UserId);
            if (student?.GroupID == Guid.Empty)
            {
                await Groups.AddToGroupAsync(Context.ConnectionId, connGroup);
            }
            Logger.Info(string.Format("用户:{0}已连接", Session.UserId));
        }

        public override async Task OnDisconnectedAsync(Exception exception)
        {
            //如果断开连接，则移除组
            await Groups.RemoveFromGroupAsync(Context.ConnectionId, connGroup);
            await base.OnDisconnectedAsync(exception);
            Logger.Info(string.Format("用户:{0}已断开", Session.UserId));
        }
    }
}
